Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

Solution:

  1. public class Solution {
  2. public int search(int[] nums, int target) {
  3. int n = nums.length;
  4. return search(nums, 0, n - 1, target);
  5. }
  6. int search(int[] nums, int lo, int hi, int target) {
  7. if (lo > hi)
  8. return -1;
  9. int mid = lo + (hi - lo) / 2;
  10. if (nums[mid] == target) {
  11. return mid;
  12. }
  13. if (nums[lo] <= nums[mid]) {
  14. if (nums[lo] <= target && target < nums[mid]) {
  15. return search(nums, lo, mid - 1, target);
  16. } else {
  17. return search(nums, mid + 1, hi, target);
  18. }
  19. } else {
  20. if (nums[mid] < target && target <= nums[hi]) {
  21. return search(nums, mid + 1, hi, target);
  22. } else {
  23. return search(nums, lo, mid - 1, target);
  24. }
  25. }
  26. }
  27. }